<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-steps :active="step" align-center class="steps" finish-status="success">
          <el-step title="待申领样本"></el-step>
          <el-step title="提交申请"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
      </el-col>
      <el-col v-show="step===0" :span="24">
        <el-card class="box-card">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                v-hasPermi="['biobank:stockClaim:query']"
                icon="el-icon-plus"
                plain
                size="mini"
                type="primary"
                @click="handlePick"
              >挑选样本
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                v-hasPermi="['biobank:stockClaim:edit']"
                :disabled="multiple"
                icon="el-icon-remove-outline"
                plain
                size="mini"
                type="success"
                @click="handleRemove"
              >批量移除
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-select v-model="queryParams.own" placeholder="请选择" size="small" @change="ownChange">
                <el-option
                  v-for="item in ownOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-col>
            <right-toolbar showSearch.sync="false" @queryTable="getList"></right-toolbar>
          </el-row>

          <el-table v-loading="loading" :data="sampleList" max-height="650" @selection-change="handleSelectionChange">
            <el-table-column align="center" type="selection" width="55"/>
            <el-table-column align="center" label="样本复份编号" min-width="110" prop="sampBackupCode"/>
            <el-table-column align="center" label="样本类型" prop="sampTypeName"/>
            <el-table-column align="center" label="样本源编号" prop="sampSourceCode"/>
            <el-table-column align="center" label="样本源名称" prop="sampSourceName"/>
            <el-table-column align="center" label="采样时间" prop="samplingTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.samplingTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="样本源类型" prop="sampSourceTypeName"/>
            <el-table-column align="center" label="样本组" prop="sampGroupName"/>
            <el-table-column align="center" label="样本量" prop="sampQuantity"/>
            <el-table-column align="center" label="样本单位" prop="sampUnit"/>
            <el-table-column :formatter="sampStateFormat" align="center" label="样本状态" prop="sampState"/>
            <el-table-column align="center" label="条码/二维码" prop="qrCode"/>
            <el-table-column align="center" label="操作" width="180">
              <template slot-scope="scope">
                <el-button
                  v-hasPermi="['biobank:stockClaim:edit']"
                  icon="el-icon-delete"
                  size="mini"
                  type="text"
                  @click="handleRemove(scope.row)"
                >移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :limit.sync="queryParams.pageSize"
            :page.sync="queryParams.pageNum"
            :total="total"
            @pagination="getList"
          />
        </el-card>
        <el-button v-hasPermi="['biobank:stockClaim:edit']" class="bottom-btn" type="success"
                   @click="submitApplication"
        >下一步：提交申请
        </el-button>

        <sample-pick :open="open" :value="sampleList" samp-state="1" @onClose="samplePickClose"
                     @onConfirm="samplePickEvent"
        ></sample-pick>
      </el-col>
      <el-col v-show="step===1" :span="24">
        <el-card class="box-card">
          <el-input v-model="approveForm.stockTitle" placeholder="请输入单据标题">
            <template slot="prepend">单据标题</template>
          </el-input>
          <editor v-model="approveForm.stockDesc" :min-height="480"/>
          <el-form :inline="true" style="margin-top: 16px">
            <el-form-item label="课题名称" prop="sampState">
              <el-select
                v-model="selectTopicId"
                clearable
                placeholder="课题名称"
                size="small"
                style="width: 240px"
                @change="topicChangeEvent"
              >
                <el-option
                  v-for="dict in topicList"
                  :key="dict.topicId"
                  :label="dict.topicName"
                  :value="dict.topicId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="课题任务">
              <el-select
                v-model="selectTaskId"
                clearable
                placeholder="课题任务"
                size="small"
                style="width: 240px"
              >
                <el-option
                  v-for="dict in taskList"
                  :key="dict.taskId"
                  :label="dict.taskName"
                  :value="dict.taskId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="保留原有位置">
              <el-switch
                v-model="approveForm.keepLocation"
                active-text="是"
                active-value="1"
                inactive-text="否"
                inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-form>
        </el-card>
        <div class="bottom-btn">
          <el-button type="primary" @click="step = 0">上一步</el-button>
          <el-button :loading="applying" type="success" @click="confirmApprove">下一步：完成</el-button>
        </div>
      </el-col>
      <el-col v-show="step===2" :span="24">
        <el-card align="center" class="box-card">
          <h1 style="margin-top: 160px">申领申请成功</h1>
          <el-button type="primary" @click="keepOut">继续申请</el-button>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Editor from '@/components/Editor'
import { listSample, updateSamples } from '@/api/biobank/sample'
import SamplePick from '@/views/biobank/sample/SamplePick'
import { addStock } from '@/api/activiti/stock'
import { listAllTopic } from '@/api/research/topic'
import { addRelate, listAllTask } from '@/api/research/task'

export default {
  name: 'StockClaim',
  components: {
    Editor,
    SamplePick
  },
  data() {
    return {
      step: 0,
      // 遮罩层
      loading: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 是否显示弹出层
      open: false,
      // 样本复份 表格数据
      sampleList: [],
      // 选中的样本复份
      selectSamples: [],
      // 审批表单
      approveForm: {},
      // 样本状态
      sampStateOptions: [],
      // 课题名称列表
      topicList: [],
      // 选中的课题
      selectTopicId: undefined,
      // 课题任务列表
      taskList: [],
      // 选中的课题任务
      selectTaskId: undefined,
      // 申请中
      applying: false,
      ownOptions: [
        {
          value: '0',
          label: '我的'
        },
        {
          value: '1',
          label: '所有'
        }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'updateTime',
        isAsc: 'DESC',
        sampState: '6',
        stockState: '0',
        own: '0' // 0-我的 1-所有
      }
    }
  },
  created() {
    this.getDicts('sample_state').then(response => {
      this.sampStateOptions = response.data
    })
    this.getList()
    listAllTopic().then(response => {
      this.topicList = response.data
    })
  },
  methods: {
    // 课题选择事件
    topicChangeEvent() {
      this.taskList = []
      this.selectTaskId = undefined
      if (!this.selectTopicId) {
        return false
      }
      listAllTask(this.selectTopicId).then(response => {
        this.taskList = response.data
      })
    },
    // 样本所属人切换
    ownChange() {
      this.getList()
    },
    // 获取待申领样本
    getList() {
      this.loading = true
      listSample(this.queryParams).then(response => {
        this.sampleList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 样本状态状态字典翻译
    sampStateFormat(row, column) {
      return this.selectDictLabel(this.sampStateOptions, row.sampState)
    },
    // 挑选样本
    handlePick() {
      this.open = true
    },
    // 批量移除
    handleRemove(row) {
      let sampBackups
      if (row.sampBackupId) {
        sampBackups = [row]
      } else {
        sampBackups = this.selectSamples
      }
      this.$confirm('是否确认移除选中的样本复份', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        sampBackups.forEach(item => {
          item.sampState = this.GLOBAL.SAMPLE.NORMAL//'1'
        })
        return updateSamples(sampBackups)
      }).then(() => {
        this.getList()
        this.msgSuccess('移除成功')
      })
    },
    // 多选框选中事件
    handleSelectionChange(selection) {
      this.selectSamples = selection
      this.multiple = !selection.length
    },
    // 选择样本对话框取消事件
    samplePickClose() {
      this.open = !this.open
    },
    // 样本挑选
    samplePickEvent(selection) {
      selection.forEach((item, index) => {
        item.sampState = this.GLOBAL.SAMPLE.TO_CLAIM// '6'
      })
      updateSamples(selection).then(response => {
        this.open = !this.open
        selection.forEach((item, index) => {
          if (this.sampleList.indexOf(item) === -1) {
            this.sampleList.push(item)
          }
        })
      })
    },
    // 下一步 提交申请
    submitApplication() {
      if (!this.selectSamples || this.selectSamples.length === 0) {
        this.$message.warning('请先选择待申领样本')
        return false
      }
      this.step = 1
      this.$set(this.approveForm, 'stockTitle', this.$store.getters.nickName + '的样本申领申请')
      this.approveForm.keepLocation = this.GLOBAL.KEEP_LOCATION// 默认保留位置
    },
    // 下一步 完成
    confirmApprove() {
      this.approveForm.stockType = this.GLOBAL.STOCK_TYPE.CLAIM//"claim"
      this.approveForm.sampleBackups = this.selectSamples

      this.applying = true
      addStock(this.approveForm).then(response => {
        if (this.selectTaskId) {
          let params = []
          this.selectSamples.forEach((item, index) => {
            let param = {}
            param.taskId = this.selectTaskId
            param.sampBackupId = item.sampBackupId
            params.push(param)
          })
          return addRelate(params)
        } else {
          return Promise.resolve()
        }
      }, error => {
        this.applying = false
      }).then(res => {
        this.$message.success(`申领申请提交成功`)
        this.applying = false
        this.step = 2
      })
    },
    // 继续申领
    keepOut() {
      // this.$router.go(0); // 刷新界面
      this.step = 0
      this.$store.dispatch('tagsView/delCachedView', this.$route).then(() => {
        this.$nextTick(() => {
          this.$router.replace({
            path: '/redirect' + this.$route.fullPath
          })
        })
      })
    }
  }
}
</script>

<style scoped>
.box-card {
  margin-left: 7px;
  margin-right: 7px;
  min-height: 720px;
}

.bottom-btn {
  margin-right: 7px;
  margin-top: 15px;
  float: right
}

.steps {
  width: 80%;
  margin: 10px auto;
}

/deep/ .el-input--small .el-input__inner {
  height: 29px;
  line-height: 29px;
}
</style>
